package com.ry.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ry.core.base.model.BaseModel;

/**
 * 对象工具类
 * 
 * @author chengl
 * @Date 2011-8-30
 * @version 1.0
 */
public class ObjectUtils {

	/**
	 * 把对象转成map，使用对象id作为key
	 * 
	 * @param <T>
	 * @param list
	 * @return
	 */
	public static <T extends BaseModel> Map<String, T> list2map(List<T> list) {
		Map<String, T> map = new HashMap<String, T>();
		for (T obj : list) {
			map.put(obj.getId(), obj);
		}
		return map;
	}

	/**
	 * 通过反射拷贝对象
	 * 
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T copy(T object) throws Exception {
		Class<?> classType = object.getClass();

		T objectCopy = (T) classType.getConstructor(new Class[] {})
				.newInstance(new Object[] {});

		// 获取对象的所有成员变量
		Field[] fields = classType.getDeclaredFields();
		for (Field field : fields) {
			String name = field.getName();// 获得成员变量的名称
			String firstLetter = name.substring(0, 1).toUpperCase();// 将属性的首字母变为大写

			String getMethodName = "get" + firstLetter + name.substring(1);
			String setMethodeName = "set" + firstLetter + name.substring(1);

			Method getMethod = classType.getMethod(getMethodName,
					new Class[] {});
			Method setMethod = classType.getMethod(setMethodeName,
					new Class[] { field.getType() });

			Object value = getMethod.invoke(object, new Object[] {});
			setMethod.invoke(objectCopy, new Object[] { value });
		}

		return objectCopy;
	}

	/**
	 * 深度复制
	 * 
	 * @param <T>
	 * @param srcObj
	 * @return
	 */
	public static <T> T depthClone(T srcObj) {
		T cloneObj = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(out);
			oo.writeObject(srcObj);

			ByteArrayInputStream in = new ByteArrayInputStream(
					out.toByteArray());
			ObjectInputStream oi = new ObjectInputStream(in);
			cloneObj = (T) oi.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return cloneObj;
	}

	/**
	 * 根据属性名获取属性值
	 * */
	private static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取属性类型(type)，属性名(name)，属性值(value)的map组成的list
	 * */
	private static List<Map> getFiledsInfo(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		String[] fieldNames = new String[fields.length];
		List<Map> list = new ArrayList();
		Map infoMap = null;
		for (int i = 0; i < fields.length; i++) {
			infoMap = new HashMap();
			infoMap.put("type", fields[i].getType().toString());
			infoMap.put("name", fields[i].getName());
			infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
			list.add(infoMap);
		}
		return list;
	}

	/**
	 * 获取属性名数组
	 * */
	private static String[] getFiledName(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		String[] fieldNames = new String[fields.length];
		for (int i = 0; i < fields.length; i++) {
			System.out.println(fields[i].getType());
			fieldNames[i] = fields[i].getName();
		}
		return fieldNames;
	}

	/**
	 * 获取对象的所有属性值，返回一个对象数组
	 * */
	public static Object[] getFiledValues(Object o) {
		String[] fieldNames = ObjectUtils.getFiledName(o);
		Object[] value = new Object[fieldNames.length];
		for (int i = 0; i < fieldNames.length; i++) {
			value[i] = ObjectUtils.getFieldValueByName(fieldNames[i], o);
		}
		return value;
	}

	/**
	 * 获取对象的所有不为空的属性值，返回一个map
	 * */
	public static Map<String, Object> getFiledNotNullValues(Object o) {
		List<Map> fields = ObjectUtils.getFiledsInfo(o);
		Map<String, Object> m = new HashMap<String, Object>();
		for (Map mf : fields) {
			String n = (String) mf.get("name");
			Object v = mf.get("value");
			String t = (String) mf.get("type");
			if (!t.contains("survey") && !t.equals("interface java.util.List")
					&& null != v) {
				m.put(n, v);
			}
		}
		return m;
	}
}
